<template>
  <div>
    <h3>我关联的社区</h3>
    <template v-if="signed">
      <el-card v-for="community in communities" :key="community.id" class="community-card mini">
        <div class="flex align-items-center">
          <el-avatar :src="community.avatar" shape="square" class="shrink-0" />
          <div class="m-l-10">
            <router-link class="title link" :to="`/${$rp.COMMUNITIES}/${community.id}`">
              {{ community.title }}
            </router-link>
            <div class="f-mini info-deep">社区人数： {{ community.counts.members }}</div>
          </div>
        </div>
      </el-card>
    </template>
    <template v-else>
      <el-button size="mini" type="primary" @click="$router.push('/users/sign_in')">登录</el-button>
    </template>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import * as format from '../format';

export default {
  name: 'RelatedCommunities', // 我关联的社区
  data() {
    return {
      communities: [], // 社区列表
    };
  },
  computed: {
    ...mapState(['currentUser']),
    signed() { return Object.keys(this.currentUser).length; },
  },
  methods: {
    // 加载我关联的社区列表
    loadCommunities() {
      this.$api.communities.index({ type: 'currentUser' })
        .then((res) => {
          this.communities = format.formatCommunities(res.data);
          this.pagination.currentPage = res.kaminari.current_page;
          this.pagination.pageCount = res.kaminari.total_pages;
        })
        .catch(() => {});
    },
  },
  created() {
    if (this.signed) this.loadCommunities();
  },
};
</script>

<style></style>
